/**
 * CheckPoint Object which holds all the data related to a checkpoint. It loads the
 * measurements from the google spreadsheet.
 * @param name
 * @param totalDistances the distance of this checkpoint from the start per categories. Because a checkpoint can participate in more categories we need to
 * specify it's distance from the start in every category. This param is an object with the categories as keys, distances as values. 
 */
function CheckPoint(name, totalDistances, key, previousCheckPoint){
    this.name = name;
    this.totalDistances = totalDistances;
    this.key = key;
    this.previousCheckPoint = previousCheckPoint == null ? this : previousCheckPoint;
    this.distanceFromPrevious = totalDistances - this.previousCheckPoint.totalDistances;
}

CheckPoint.prototype.getEditorUrl = function(){
    return 'https://spreadsheets.google.com/ccc?key=' + this.key + '&hl=hu';
}

function loadCheckPointData(year, nextMethod){
    var cpCount = checkPoints.length ;
    var loadedCount = 0;
    CheckPoint.loadNotifier = function(){
        $('#progress').progressBar(100 * (++loadedCount) / cpCount);
        if (loadedCount == cpCount) {
            $("#loading").fadeOut(1500);
            nextMethod();
        }
    }
    $.each(checkPoints, function(){
        this.loadDataFromSpreadsheet(year);
    });
}

/** Parses the jsonp atom feed coming from the spreadsheet data api.
 * Removes the first row and shifts the table 1 row up so the first data row has the index 0
 */
CheckPoint.prototype.parseRawSpreadsheetData = function(rawdata){
    this.data = new Array();
    var length = 0;
    if (rawdata.feed && rawdata.feed.entry) {
        length = rawdata.feed.entry.length;
    }
    this.measurementCount = 0;
    for (var i = 0; i < length; i++) {
        var entry = rawdata.feed.entry[i];
        var row = parseInt(entry.gs$cell.row) - 2;//shift up with 2 rows
        if (row == -1) {//Do not store the headers
            continue;
        }
        var col = parseInt(entry.gs$cell.col);
        var value = entry.content.$t;
        if (col == 1) {
            this.data[row] = new Array();
            ++this.measurementCount;
        }
        try {
            this.data[row][col] = value;
        } catch (err) {
            ; //TODO: nem vart hiba volt!
        }
    }
}

/** Creates alternative internal represantations of the data to allow faster access and calculates some information from the raw data*/
CheckPoint.prototype.preprocessData = function() {
    this.measurementsByCompetitor = new Array();
    this.relativeTimesByCompetitor = new Array();
    this.sectionTimesByCompetitor = new Array();
    var competitorId = 0;
    for (i = 0; i < this.measurementCount; ++i) {
        competitorId = 0;
        //storing measurements in timestamps into the column 4
        try {
            var measurement = new Date();
            var measurementTime = Date.parse("4 Jun 2011 " + this.data[i][2]);
            if ( "5" == this.data[i][3] || "6" == this.data[i][3] ) {
                measurementTime = Date.parse("5 Jun 2011 " + this.data[i][2]);
            }

            measurement.setTime(measurementTime);
            this.data[i][4] = measurement;
            competitorId = parseInt(this.data[i][1]);
            this.measurementsByCompetitor[competitorId] = measurement;
            this.relativeTimesByCompetitor[competitorId] = new Date(measurementTime - checkPoints[0].measurementsByCompetitor[competitorId].getTime() - 60*60*1000 );
            this.sectionTimesByCompetitor[competitorId] = new Date(measurementTime - this.previousCheckPoint.measurementsByCompetitor[competitorId].getTime() - 60*60*1000 );
        } catch (err) {
        }
        
        //Storing the measurement in the competitor object as the last known measurement
        try {
            var lastCp = competitorsById[competitorId].lastCheckPoint;
            var cat = competitorsById[competitorId].category;
            if (lastCp.totalDistances[cat] <= this.totalDistances[cat]) {
                competitorsById[competitorId].lastMeasurementTime = measurementTime;
                competitorsById[competitorId].lastCheckPoint = this;
            }
        } catch (err) {
        }
    }
}

/** Loads the data from the spreadsheet of the checkpoint asynchronously */
CheckPoint.prototype.loadDataFromSpreadsheet = function(year){
    var callback = ('spreadSheet' + this.key + 'Loaded').replace(/-/g, '_');
    var obj = this;
    CheckPoint[callback] = function(data){
        obj.parseRawSpreadsheetData(data);
        obj.preprocessData();
        CheckPoint.loadNotifier(data);
        CheckPoint[callback] = null;
    }
    var url = 'http://spreadsheets.google.com/feeds/cells/' + this.key + '/'+ getWorksheetIndex(year) + '/public/values?alt=json-in-script&callback=CheckPoint.' + callback;
    $.getScript(url);
}

checkPoints = new Array();
var lastCP = null;

checkPoints[0] = lastCP = new CheckPoint("Rajt, Kisnána", {
    '55': 0,
    '88': 0,
    '115': 0
}, 'rkBx7rPdQBX_sdG42xKGcTw', lastCP);
checkPoints.push(lastCP = new CheckPoint("Jagus", {
    '55': 6.97,
    '88': 6.97,
    '115': 6.97
}, 'rHUXntdKskPq-g7cjjGuogg', lastCP));
checkPoints.push(lastCP = new CheckPoint("Oroszlánvár", {
    '55': 8.03,
    '88': 8.03,
    '115': 8.03
}, 'rU0c7yO9lnE4JMjXC9vDb5A', lastCP));
checkPoints.push(lastCP = new CheckPoint("Kékestető",{
    '55': 17.15,
    '88': 17.15,
    '115': 17.15
} , 'rp3Oz3r_RbRXWMHISByz3CQ', lastCP));
checkPoints.push(lastCP = new CheckPoint("Parádsasvár", {
    '55': 26.46,
    '88': 26.46,
    '115': 26.46
}, 'rpLiDyxpzck2Q_KXS1qpNjw', lastCP));
checkPoints.push(lastCP = new CheckPoint("Galyatető, Gertrud vh.", {
    '55': 29.2,
    '88': 29.2,
    '115': 29.2
}, 'rLvP4K9n084oPRUHcrwH01Q', lastCP));
checkPoints.push(lastCP = new CheckPoint("Mátraalmás",{
    '55': -1,
    '88': 34.83,
    '115': 34.83
}, 'rUMp4t_2pXVK2sIyrk2sJQQ', lastCP));
checkPoints.push(lastCP = new CheckPoint("Galyatető",{
    '55': -1,
    '88': 38.74,
    '115': 38.74
}, 'ryajsrcMAa70v2-dTddDytA', lastCP));
checkPoints.push(lastCP = new CheckPoint("Hatökör-ura", {
    '55': -1,
    '88': 45.76,
    '115': 45.76
}, 'rNl2Max4wF5_N-lFFYxrx2Q', lastCP));
checkPoints.push(lastCP = new CheckPoint("Mátraháza, Tölgy kisvendéglő",{
    '55': -1,
    '88': 47.47,
    '115': 47.47
}, 'ri4dTnHISYkh4uNqZYHmc1w', lastCP));
checkPoints.push(lastCP = new CheckPoint("Lajosháza", {
    '55': -1,
    '88': 51.93,
    '115': 51.93
}, 'rKes8IbKtYMR10JLKOLKizw', lastCP));
checkPoints.push(lastCP = new CheckPoint("Mátraszentimre, Vadvirág-th.",{
    '55': 35.88,
    '88': 60.54,
    '115': 60.54
}, 'rdCY4iapyN4kmvcaDH0K0oQ', lastCP));
checkPoints.push(lastCP = new CheckPoint("Szorospatak",{
    '55': -1,
    '88': 67.67,
    '115': 67.67
}, 'roUMt96ikA35-LCId9m3Tig', lastCP));
checkPoints.push(lastCP = new CheckPoint("Ágasvári-th.",{
    '55': -1,
    '88': 71.9,
    '115': 71.9
}, 'r172GMFtdIeMLDvNSggDJAA', lastCP));
checkPoints.push(lastCP = new CheckPoint("Ágasvár",{
    '55': -1,
    '88': 72.46,
    '115': 72.46
}, 'rRIV9hAScChqx3flosccHTA', lastCP));
checkPoints.push(lastCP = new CheckPoint("Fallóskút", {
    '55': -1,
    '88': 76.11,
    '115': 76.11
}, 'rXbQCan4SfDpu6J3yLrdPMg', lastCP));
checkPoints.push(lastCP = new CheckPoint("Hidegkúti th.",{
    '55': 45.01,
    '88': 81.94,
    '115': 81.94
}, 'rkwgMHrdPh67yXTr3bLMXpA', lastCP));
checkPoints.push(lastCP = new CheckPoint("Muzsla",{
    '55': -1,
    '88': -1,
    '115': 90.01
}, 'rvp471CxGaSFKfUCPT_ADGQ', lastCP));
checkPoints.push(lastCP = new CheckPoint("Diós-patak",{
    '55': -1,
    '88': -1,
    '115': 95.53
}, 'r_J5HDj-SaFx1xS2AzHtf-g', lastCP));
checkPoints.push(lastCP = new CheckPoint("Havas",{
    '55': -1,
    '88': -1,
    '115': 104.51
}, 'rmBjdmu2TzG1D7KWX30YADA', lastCP));
checkPoints.push(lastCP = new CheckPoint("Fajzatpuszta",{
    '55': -1,
    '88': -1,
    '115': 107.66
}, 'rhytLj-mD9fkUtIHU2k4Bdg', lastCP));
checkPoints.push(lastCP = new CheckPoint("Káva", {
    '55': -1,
    '88': 80.79,
    '115': 110.06
}, 'r0kaOaZBYBnXWsh437POV-Q', lastCP));
checkPoints.push(lastCP = new CheckPoint("Tót-hegyes",{
    '55': 47.71,
    '88': 84.64,
    '115': 113.91
}, 'rpDYpnAko73ye5UhlHfeugw', lastCP));
checkPoints.push(lastCP = new CheckPoint("Világoshegy",{
    '55': 50.76,
    '88': 87.69,
    '115': 116.96
}, 'r_txl0wQ0P2nXWJYmAbBIuw', lastCP));
checkPoints.push(lastCP = new CheckPoint("Gyöngyöstarján", {
    '55': 57.84,
    '88': 94.77,
    '115': 124.04
}, 'rS-VC6Lz6EmbcsyE7Awqyvw', lastCP));



